package com.fat.controller;

import com.fat.pojo.Result;
import com.fat.pojo.User;
import com.fat.service.UserService;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.Pattern;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Objects;


/**
 * 用户控制器
 */
@RestController
@RequestMapping("/user")
@Validated
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 注册
     */
    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^\\S{5,16}") String username, @Pattern(regexp = "^\\S{5,16}") String password) {
        //查询用户名是否存在
        User u = userService.findByUsername(username);
        if (Objects.isNull(u)){
            //用户名不存在，可以注册
            userService.register(username,password);
            return Result.success();
        }else{
            //用户名存在，不可以注册
            return Result.error("用户名已存在");
        }

    }

    /**
     * 登录
     */
    @PostMapping("/login")
    public Result login(@Pattern(regexp = "^\\S{5,16}") String username, @Pattern(regexp = "^\\S{5,16}") String password) {
        return userService.login(username,password);
    }

    /**
     * 获取用户信息
     */
    @GetMapping("/userInfo")
    public Result userInfo() {
        return userService.getUserInfo();
    }

    /**
     * 用户信息修改
     */
    @PutMapping("/update")
    public Result update(@RequestBody @Validated User user) {
        return userService.update(user);
    }

    /**
     * 修改头像
     */
    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam @URL String avatarUrl) {
        return userService.updateAvatar(avatarUrl);
    }

    /**
     * 更新密码
     */
    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String,String> map) {
        String oldPwd = map.get("old_pwd");
        String newPwd = map.get("new_pwd");
        String rePwd = map.get("re_pwd");
        return userService.updatePwd(oldPwd,newPwd,rePwd);
    }


}
